﻿Imports Word = Microsoft.Office.Interop.Word
Imports Microsoft.Office.Interop.Word

Public Class Form1

    Dim TemplateFile As String
    Dim TemplateFolder As String
    Dim oWord As Word.Application
    Dim ContractType As Integer
    Dim inputSum As Double
    Dim result As String
    Dim fCops As String
    Dim fWrtCost As String
    Dim fShortName As String
    Dim fShortDadName As String
    Dim fInfPosit As String
    Dim NDSFlag As Boolean
    Dim fSerivceCost As Double
    Dim fSerivceWrtCost As String
    Dim fServiceNDS As Double
    Dim fServiceWrtNDS As String
    Dim FSoftCost As Double
    Dim fSoftCostWrt As String





    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        TemplateFolder = "d:\DogCreator\"
        FDatePicker.Visible = True
        ComboBox2.SelectedIndex = 0

    End Sub

    Private Sub CreateButt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateButt.Click
        ' комментарий
        'Выбор шаблона
        Select Case ComboBox2.SelectedIndex
            Case 0
                TemplateFile = "sublic_100.dotx"
                NDSFlag = False

            Case 1
                TemplateFile = "lic_service_100.dotx"
                NDSFlag = True
        End Select




        oWord = New Word.Application
        oWord.Documents.Add(Template:=TemplateFolder & TemplateFile)
        oWord.Documents(1).Activate()
        oWord.ActiveDocument.SaveAs(TemplateFolder + "Вг-" + Strings.Right(FDatePicker.Value.Year.ToString, 2) + "-" + FNumBox.Text)

        oWord.Visible = True
        ContractType = 0

        'запуск поиска и замены
        ReplaceWords(ContractType, oWord.ActiveDocument)



        oWord.Documents.Save(True)

    End Sub

    Function MonthWritten(ByVal month As Integer)
        Dim mw As String
        Dim months = "января февраля марта апреля мая июня июля августа сентября октября ноября декабря"
        Dim monthsArray() As String

        monthsArray = Split(months, " ")

        mw = monthsArray(month - 1)
        Return mw
    End Function

    Function ReplaceWords(ByVal mode As Integer, ByVal Doc As Word.Document)

        Dim fWrMonth As String
        Dim mnth As String
        Dim dy As String


        If FDatePicker.Value.Month <= 9 Then
            mnth = "0" & FDatePicker.Value.Month.ToString
        Else : mnth = FDatePicker.Value.Month.ToString
        End If

        If FDatePicker.Value.Day <= 9 Then
            dy = "0" & FDatePicker.Value.Day.ToString
        Else : dy = FDatePicker.Value.Day.ToString
        End If

        'Заполнеие номеров и дат
        fWrMonth = MonthWritten(FDatePicker.Value.Month)

        Doc.Content.Find.Execute(FindText:="dNum", ReplaceWith:=Strings.Right(FDatePicker.Value.Year.ToString, 2) & "-" & FNumBox.Text, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dDateDay", ReplaceWith:=dy, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dWrMonth", ReplaceWith:=fWrMonth, Replace:=1)
        Doc.Content.Find.Execute(FindText:="dDateY", ReplaceWith:=FDatePicker.Value.Year, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dDateMonth", ReplaceWith:=mnth, Replace:=2)

        'Заполнение преамбулы
        Select Case FFormShortBox.SelectedIndex
            Case 0
                Doc.Content.Find.Execute(FindText:="dForm", ReplaceWith:="Общество с ограниченной ответственностью", Replace:=2)
            Case 1
                Doc.Content.Find.Execute(FindText:="dForm", ReplaceWith:="Открытое акционерное общество", Replace:=2)
            Case 2
                Doc.Content.Find.Execute(FindText:="dForm", ReplaceWith:="Закрытое акционерное общество", Replace:=2)
        End Select


        Doc.Content.Find.Execute(FindText:="dCompanyName", ReplaceWith:=FCompanyNameBox.Text, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dPosit", ReplaceWith:=ComboBox1.Text, Replace:=2)

        Doc.Content.Find.Execute(FindText:="dFname", ReplaceWith:=FFnameBox.Text, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dName", ReplaceWith:=FNameBox.Text, Replace:=1)
        Doc.Content.Find.Execute(FindText:="dDadName", ReplaceWith:=FDadNameBox.Text, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dActBase", ReplaceWith:=FActBaseBox.Text, Replace:=2)

        Select Case ComboBox1.Text
            Case "Генерального директора"
                fInfPosit = "Генеральный директор"
            Case "Директора"
                fInfPosit = "Директор"
            Case "Исполнительного директора"
                fInfPosit = "Исполнительный директор"
        End Select
        Doc.Content.Find.Execute(FindText:="dInfPosit", ReplaceWith:=fInfPosit, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dShortName", ReplaceWith:=Strings.Left(FNameBox.Text, 1), Replace:=2)
        Doc.Content.Find.Execute(FindText:="dShortDadName", ReplaceWith:=Strings.Left(FDadNameBox.Text, 1), Replace:=2)
        Doc.Content.Find.Execute(FindText:="dInfFname", ReplaceWith:=fInfFNameBox.Text, Replace:=2)


        'Заполнение стоимости
        Dim cops = TextBox4.Text

        result = TextBox2.Text & "," & cops.ToString
        Try
            inputSum = Double.Parse(result)

        Catch d As FormatException
            MsgBox("Unable to convert  to a Double.")
        Catch d As OverflowException
            MsgBox(" is outside the range of a Double.")

        End Try
        fWrtCost = Propis.Propis(inputSum)
        Doc.Content.Find.Execute(FindText:="dCost", ReplaceWith:=TextBox2.Text, Replace:=2)
        Doc.Content.Find.Execute(FindText:="dWrtCost", ReplaceWith:=fWrtCost, Replace:=2)

        ' Расчет стоимости Прав и Услуг
        If NDSFlag = True Then
            Dim NDS As String

            NDS = NDSBoxRub.Text & "," & NDSBoxCops.Text
            Try
                fSerivceCost = ServiceCostCalc(Double.Parse(NDS))
            Catch d As FormatException
                MsgBox("Unable to convert  to a Double.")
            Catch d As OverflowException
                MsgBox(" is outside the range of a Double.")

            End Try

            FSoftCost = SoftwareCostCalc(inputSum, Double.Parse(NDS))


            'Заполнение стоимости Прав и Услуг и НДС
            fSerivceWrtCost = Propis.Propis(fSerivceCost)
            fSoftCostWrt = Propis.Propis(FSoftCost)
            fServiceWrtNDS = Propis.Propis(Double.Parse(NDS))


            Doc.Content.Find.Execute(FindText:="dSerivceCost", ReplaceWith:=fSerivceCost, Replace:=2)
            Doc.Content.Find.Execute(FindText:="dSerivceWrtCost", ReplaceWith:=fSerivceWrtCost, Replace:=2)
            Doc.Content.Find.Execute(FindText:="dServiceNDS", ReplaceWith:=NDSBoxRub.Text, Replace:=2)
            Doc.Content.Find.Execute(FindText:="dSerivceWrtNDS", ReplaceWith:=fServiceWrtNDS, Replace:=2)

            Doc.Content.Find.Execute(FindText:="dSoftCost", ReplaceWith:=FSoftCost, Replace:=2)
            Doc.Content.Find.Execute(FindText:="dWrtSoftCost", ReplaceWith:=fSoftCostWrt, Replace:=2)
        End If

        'поиск и замена в колонтитуле
        Doc.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryFooter
        Doc.ActiveWindow.Selection.Find.Execute(FindText:="dNum", ReplaceWith:=Strings.Right(FDatePicker.Value.Year.ToString, 2) & "-" & FNumBox.Text, Replace:=2)
        Doc.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument

        'Реквизиты
        Doc.Content.Find.Execute(FindText:="dShortForm", ReplaceWith:=FFormShortBox.Text, Replace:=2)


        Return 0

    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub

    Private Sub FFnameBox_LostFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FFnameBox.LostFocus
        fInfFNameBox.Text = Strings.Left(FFnameBox.Text, Strings.Len(FFnameBox.Text) - 1)
    End Sub

    Function ServiceCostCalc(NDSSum As Double) ' расчет стоимости Услуг
        Dim SrvCost As Double

        SrvCost = Math.Truncate(NDSSum * 6.5556)

        Return SrvCost
    End Function

    Function SoftwareCostCalc(ContractSum As Double, NDSSum As Double) ' Расчет стоимости Прав

        Dim SrvCost As Double
        Dim SoftCost As Double

        SrvCost = Math.Truncate(NDSSum * 6.5556)
        SoftCost = ContractSum - SrvCost

        Return SoftCost
    End Function
  
End Class
